package com.mission.datasave

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mission.datasave.databinding.ActivityFileSaveBinding
import java.io.*

/**
 * Created by KevenTao on 1/7/21.
 */
class FileActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityFileSaveBinding

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val intent = Intent(context, FileActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityFileSaveBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        val editContent = loadFile()
        if (!editContent.isEmpty()) {
            mBinding.inputText.setText(editContent)
            mBinding.inputText.setSelection(editContent.length)
            Toast.makeText(this, "Load Success！！！", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        saveFile()
    }

    /**
     * 保存文件
     */
    private fun saveFile() {
        try {
            val outPut = openFileOutput("data_file", Context.MODE_PRIVATE);
            val bufferWriter = BufferedWriter(OutputStreamWriter(outPut));
            //use函数会自动调用close
            bufferWriter.use {
                it.write(mBinding.inputText.text.toString())
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 读取文件
     */
    private fun loadFile(): String {
        val content = StringBuilder()
        try {
            val input = openFileInput("data_file")
            val bufferReader = BufferedReader(InputStreamReader(input))
            bufferReader.use {
                it.forEachLine {
                    content.append(it)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content.toString()
    }
}